import api from '../../api';
import { message } from 'antd';
import accounting from 'accounting';

export default {
  namespace: 'investmentAdviserReportM',
  state: {
    columns: [],
    dataSource: [],
    adviserList: [], // 租户下的所有投顾
  },
  effects: {
    // 查询投顾报表
    *queryReportTable({ payload }, { call, put }) {
      const res = yield call(api.investmentAdviserReport.queryReportTable, payload);
      let colunms = [];
      if (payload?.queryConditions?.type === '1') {
        colunms = [
          { key: 'product', title: '产品名称' },
          { key: 'adviserid', title: '投顾名称' },
          { key: 'secutype', title: '资产类别' },
          {
            key: 'tradingcode',
            title: '证券代码',
            render: (text, record) => {
              return !['1', '2'].includes(record.type) ? text : '';
            },
          },
          {
            key: 'secuabbr',
            title: '证券名称',
            render: (text, record) => {
              return !['1', '2'].includes(record.type) ? text : '';
            },
          },
          {
            key: 'costprice',
            title: '成本价',
            align: 'right',
            render: (text, record) => {
              if (text !== 0 && !text) {
                return record.secutype == '99' ? '--' : '';
              }
              return accounting.formatNumber(Number(text), 2);
            },
          },
          {
            key: 'quantity',
            title: '持仓数量',
            align: 'right',
            render: (text, record) => {
              if (text !== 0 && !text) {
                return ['5', '6', '13', '14', '3', '4', '99'].includes(record.secutype) ? '--' : '';
              }
              return ['5', '6', '13', '14', '3', '4', '99'].includes(record.secutype) ? '--' : accounting.formatNumber(Number(text), 2);
            },
          },
          {
            key: 'totalmktval',
            title: '总市值',
            align: 'right',
            render: (text, record) => {
              if (text !== 0 && !text) {
                return '';
              }
              return accounting.formatNumber(Number(text), 2);
            },
          },
          { key: 'totalProfit', title: '总盈亏', type: 'updownText', noData: '--', splitStyle: true },
          {
            key: 'annualYield',
            title: '年化收益率',
            render: (text, record) => {
              if (text === null || text === undefined || !['1', '2'].includes(record.type)) {
                return '';
              } else {
                if (isNaN(text)) {
                  return text;
                } else {
                  return (Number(text) * 100).toFixed(2) + '%';
                }
              }
            },
          },
        ];
      } else {
        colunms = [
          { key: 'adviserid', title: '投顾名称' },
          { key: 'product', title: '产品名称' },
          { key: 'secutype', title: '资产类别' },
          {
            key: 'tradingcode',
            title: '证券代码',
            render: (text, record) => {
              return !['1', '2'].includes(record.type) ? text : '';
            },
          },
          {
            key: 'secuabbr',
            title: '证券名称',
            render: (text, record) => {
              return !['1', '2'].includes(record.type) ? text : '';
            },
          },
          {
            key: 'costprice',
            title: '成本价',
            align: 'right',
            render: (text, record) => {
              if (text !== 0 && !text) {
                return record.secutype == '99' ? '--' : '';
              }
              return accounting.formatNumber(Number(text), 2);
            },
          },
          {
            key: 'quantity',
            title: '持仓数量',
            align: 'right',
            render: (text, record) => {
              if (text !== 0 && !text) {
                return ['5', '6', '13', '14', '3', '4', '99'].includes(record.secutype) ? '--' : '';
              }
              return ['5', '6', '13', '14', '3', '4', '99'].includes(record.secutype) ? '--' : accounting.formatNumber(Number(text), 2);
            },
          },
          {
            key: 'totalmktval',
            title: '总市值',
            align: 'right',
            render: (text, record) => {
              if (text !== 0 && !text) {
                return '';
              }
              return accounting.formatNumber(Number(text), 2);
            },
          },
          { key: 'totalProfit', title: '总盈亏', type: 'updownText', noData: '--', splitStyle: true },
          {
            key: 'annualYield',
            title: '年化收益率',
            render: (text, record) => {
              if (text === null || text === undefined || !['1', '2'].includes(record.type)) {
                return '';
              } else {
                if (isNaN(text)) {
                  return text;
                } else {
                  return (Number(text) * 100).toFixed(2) + '%';
                }
              }
            },
          },
        ];
      }
      let timestamp = new Date().getTime();
      let tempArr = res?.data?.dataSource?.InvestmentAdviserReport || [];
      let expandedRowKeys = [];
      tempArr.forEach((item, i) => {
        item.key = timestamp + '0' + i;
        expandedRowKeys.push(item.key);
        if (Array.isArray(item.children)) {
          item.children.forEach((obj, j) => {
            obj.key = item.key + j;
            expandedRowKeys.push(obj.key);
            if (Array.isArray(obj.children)) {
              obj.children.forEach((stock, k) => {
                stock.key = obj.key + k;
                delete stock.children;
              });
            }
          });
        }
      });
      if (res?.code == '0') {
        yield put({
          type: 'save',
          payload: {
            dataSource: tempArr,
            columns: colunms,
            expandedRowKeys: expandedRowKeys,
          },
        });
        return;
      }
      message.error(res?.msg || '查询失败！');
      console.error(`投顾报告查询失败！，失败原因：${res?.msg}`, '接口名称： queryReportTable gateway/maat-report/v1/queryReportTable');
    },
    // 查询租户下所有投顾名称
    *getInvestmentAdviserInfo({ payload }, { call, put }) {
      const res = yield call(api.investmentAdviserReport.getInvestmentAdviserInfo, payload);
      if (res?.code == '0') {
        let tempArr = (res?.data.dataSource || []).map((item) => {
          return item.advisername;
        });
        tempArr = [...new Set(tempArr)];
        yield put({
          type: 'save',
          payload: {
            adviserList: tempArr.map((item) => {
              return { title: item, value: item };
            }),
          },
        });
        return;
      }
      console.error(`查询租户下所有投顾名称失败！，失败原因：${res?.msg}`, '接口名称： getInvestmentAdviserInfo gateway/portfolio-server/portfolioInfo/getInvestmentAdviserInfo');
    },
    // 获取前一个交易日
    *getTradingDay({ payload, callback }, { call, put }) {
      const res = yield call(api.getTradingDate, payload);
      if (res && res.success) {
        callback(res.data);
      } else {
        message.error(res?.message || '获取前一个交易日失败！');
      }
    },
    // 获取前一周交易日
    *getSevenTradeDate({ payload, callback }, { call, put }) {
      const res = yield call(api.getSevenTradeDate, payload);

      if (res && res.code == '0') {
        callback(res.data);
      } else {
        message.error(res?.message || '获取前一周交易日失败！');
      }
    },
  },
  reducers: {
    save(state, { payload }) {
      return {
        ...state,
        ...payload,
      };
    },
  },
};
